package com.tjbank.cssys.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.tjbank.cssys.mybatis.mapper.IamRelationshipMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.tjbank.cssys.api.RelationIDService;
import com.tjbank.cssys.dto.OrganDTO;
import com.tjbank.cssys.dto.PermissionDTO;
import com.tjbank.cssys.dto.RoleDTO;
import com.tjbank.cssys.entityext.DataPermParam;
import com.tjbank.cssys.mapperext.PermissionMapper;
import com.tjbank.cssys.mybatis.IamApiDao;
import com.tjbank.cssys.mybatis.IamGroupDao;
import com.tjbank.cssys.mybatis.IamMenuDao;
import com.tjbank.cssys.mybatis.IamRelationshipDao;
import com.tjbank.cssys.mybatis.entity.IamApi;
import com.tjbank.cssys.mybatis.entity.IamApiKey;
import com.tjbank.cssys.mybatis.entity.IamGroupKey;
import com.tjbank.cssys.mybatis.entity.IamMenu;
import com.tjbank.cssys.mybatis.entity.IamMenuKey;
import com.tjbank.cssys.mybatis.entity.IamRelationship;
import com.tjbank.cssys.mybatis.sqlbuilder.IamRelationshipSqlBuilder;
import com.tjbank.cssys.service.convert.OrganConvert;
import com.tjbank.cssys.service.convert.PermissionConvert;
import com.tjbank.cssys.service.enums.RelaCodeEnum;

/**
 * 关联关系ID
 * 
 * Package : com.tansun.magicube.iam.service.impl
 * 
 * @author -- lijiangtao 2020年5月19日 下午12:43:40
 *
 */
@Service
public class RelationIDServiceImpl implements RelationIDService {

    /** 关联关系 **/
    @Autowired
    private IamRelationshipDao relationshipDao;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private IamApiDao apiDao;

    @Autowired
    private IamMenuDao menuDao;

    @Autowired
    private IamGroupDao organDao;
    @Autowired
    private IamRelationshipMapper iamRelationshipMapper;

    /**
     * 根据用户ID查询角色ID集合
     * 
     * @param userId
     * @return
     * @author -- lijiangtao 2020年5月5日 下午4:41:23
     */
    @Override
    public List<String> queryRoleIdListByUserId(String userId) {
        IamRelationshipSqlBuilder sqlBuilder = new IamRelationshipSqlBuilder();
        sqlBuilder.andEntity1CodeEqualTo(userId).andRelaCodeEqualTo(RelaCodeEnum.USER_ROLE.getCode());
        return relationshipDao.selectListBySqlBuilder(sqlBuilder).stream().map(IamRelationship::getEntity2Code).collect(Collectors.toList());
    }

    /**
     * 根据角色ID查询用户ID集合
     * 
     * @param roleId
     * @return
     * @author -- lijiangtao 2020年5月9日 上午10:23:53
     */
    @Override
    public List<String> queryUserIdListByRoleId(String roleId) {
        IamRelationshipSqlBuilder sqlBuilder = new IamRelationshipSqlBuilder();
        sqlBuilder.andEntity2CodeEqualTo(roleId).andRelaCodeEqualTo(RelaCodeEnum.USER_ROLE.getCode());
        return relationshipDao.selectListBySqlBuilder(sqlBuilder).stream().map(IamRelationship::getEntity1Code).collect(Collectors.toList());
    }

    /**
     * 根据用户ID查询岗位ID集合
     * 
     * @param userId
     * @return
     * @author -- lijiangtao 2020年5月19日 下午2:49:03
     */
    @Override
    public List<String> queryPostIdByUserId(String userId) {
        IamRelationshipSqlBuilder sqlBuilder = new IamRelationshipSqlBuilder();
        sqlBuilder.andEntity1CodeEqualTo(userId).andRelaCodeEqualTo(RelaCodeEnum.USER_POST.getCode());
        return relationshipDao.selectListBySqlBuilder(sqlBuilder).stream().map(IamRelationship::getEntity2Code).collect(Collectors.toList());
    }

    /**
     * 根据岗位ID查询用户ID集合
     * 
     * @param postId
     * @return
     * @author -- lijiangtao 2020年6月19日 下午5:20:25
     */
    @Override
    public List<String> queryUserIdByPostId(String postId) {
        IamRelationshipSqlBuilder sqlBuilder = new IamRelationshipSqlBuilder();
        sqlBuilder.andEntity2CodeEqualTo(postId).andRelaCodeEqualTo(RelaCodeEnum.USER_POST.getCode());
        return relationshipDao.selectListBySqlBuilder(sqlBuilder).stream().map(IamRelationship::getEntity1Code).collect(Collectors.toList());
    }

    /**
     * 根据角色IDList查询菜单权限
     * 
     * @param roleList
     * @return
     * @author -- lijiangtao 2020年5月5日 下午4:53:19
     */
    @Override
    public List<PermissionDTO> queryMenuPermByRoleId(List<RoleDTO> roleList) {
        Set<String> rightsSet = new HashSet<>();
        roleList.forEach(role -> {
            IamRelationshipSqlBuilder sqlBuilder = new IamRelationshipSqlBuilder();
            sqlBuilder.andEntity1CodeEqualTo(role.getId()).andRelaCodeEqualTo(RelaCodeEnum.ROLE_MENU_PERM.getCode());
            List<IamRelationship> list = relationshipDao.selectListBySqlBuilder(sqlBuilder);
            list.forEach(entity -> rightsSet.add(entity.getEntity2Code()));
        });
        if (rightsSet.isEmpty()) {
            return null;
        }
        List<PermissionDTO> permissionList = PermissionConvert.INSTANCE.entitiesToDtoList(permissionMapper.queryPerission(new ArrayList<String>(rightsSet)));
        for (PermissionDTO permission : permissionList) {
            IamMenu menu = menuDao.selectByPrimaryKey(new IamMenuKey(permission.getId()));
            IamApi api = apiDao.selectByPrimaryKey(new IamApiKey(permission.getApiId()));
            permission.setMenuUrl(Objects.isNull(menu) ? null : menu.getMenuUrl());
            permission.setMenuSort(Objects.isNull(menu) ? null : menu.getMenuSort());
            permission.setApiUrl(Objects.isNull(api) ? null : api.getApiUrl());
        }
        return permissionList;
    }

    /**
     * 根据角色IDlist 查询接口权限
     * 
     * @param roleList
     * @return
     * @author -- lijiangtao 2020年5月5日 下午4:53:19
     */
    @Override
    public List<PermissionDTO> queryApiPermByRoleId(List<RoleDTO> roleList) {
        Set<String> rightsSet = new HashSet<>();
        roleList.forEach(role -> {
            IamRelationshipSqlBuilder sqlBuilder = new IamRelationshipSqlBuilder();
            sqlBuilder.andEntity1CodeEqualTo(role.getId()).andRelaCodeEqualTo(RelaCodeEnum.ROLE_API_PERM.getCode());
            List<IamRelationship> list = relationshipDao.selectListBySqlBuilder(sqlBuilder);
            list.forEach(entity -> rightsSet.add(entity.getEntity2Code()));
        });
        if (rightsSet.isEmpty()) {
            return null;
        }
        return PermissionConvert.INSTANCE.entitiesToDtoList(permissionMapper.queryPerission(new ArrayList<String>(rightsSet)));
    }

    /**
     * 根据角色IDlist 查询数据权限
     * 
     * @param roleList
     * @return
     * @author -- lijiangtao 2020年7月30日 上午11:25:55
     */
    @Override
    public List<OrganDTO> queryDataPermByRoleId(List<String> roleList, OrganDTO organDTO) {
        // 机构ID
        List<String> orgIdList = new ArrayList<>();
       /* for (String roleId : roleList) {
            IamRelationshipSqlBuilder sqlBuilder = new IamRelationshipSqlBuilder();
            sqlBuilder.andEntity1CodeEqualTo(roleId).andRelaCodeEqualTo(RelaCodeEnum.ROLE_DATA_PERM.getCode());
            orgIdList.addAll(relationshipDao.selectListBySqlBuilder(sqlBuilder).stream().map(IamRelationship::getEntity2Code).collect(Collectors.toList()));
        }*/
        Map<String,String>map =iamRelationshipMapper.selectOrginIdByuserCode(organDTO.getLoginCode());
        orgIdList.add(map.get("ID"));
        List<String> rightsList = new ArrayList<String>(new LinkedHashSet<>(orgIdList));
        if (rightsList.isEmpty()) {
            return null;
        }
        // 机构向下
        List<String> listAll = new ArrayList<>();
        for (String nodeId : rightsList) {
            listAll.addAll(permissionMapper.queryDataPerission(OrganConvert.INSTANCE.entityToNode(organDao.selectByPrimaryKey(new IamGroupKey(nodeId)))));
        }
        DataPermParam dataPerm = new DataPermParam(new ArrayList<String>(new LinkedHashSet<>(listAll)), organDTO.getCode(), organDTO.getName());
        return OrganConvert.INSTANCE.entitiesToDTOList(permissionMapper.queryDataPermByList(dataPerm));
    }

}
